package com.example.administrator.himalaya.activity;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.himalaya.adapter.MAdapter;
import com.example.administrator.himalaya.R;
import com.example.administrator.himalaya.service.guojiaService;
import com.example.administrator.himalaya.entity.castentity.bendiEntity;
import com.example.administrator.himalaya.sqlHelper.Helper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class wangluoActivity extends AppCompatActivity implements View.OnClickListener, AbsListView.OnScrollListener, Callback<bendiEntity>, AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
    private ListView mListView;
    private List<bendiEntity.ResultEntity> data;
    private boolean isButton;
    private MAdapter mAdapter;
    private int pagerNum = 1;
    private guojiaService mService;
    //    判断刷新
    private boolean isRefreshing = false;
    private SwipeRefreshLayout mRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wangluo);
        ImageView back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.listView);
        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(this);
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        mRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED, Color.YELLOW, Color.CYAN);
        mRefreshLayout.setOnRefreshListener(this);
        data = new ArrayList<>();
        mService = new Retrofit.Builder()
                .baseUrl("http://live.ximalaya.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(guojiaService.class);
        mService.getList(pagerNum, 20, 3).enqueue(this);
        mAdapter = new MAdapter(this, data);
        mListView.setAdapter(mAdapter);
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //判断listview第一个可见的条目是否是第一个条目
                if (mListView.getFirstVisiblePosition() == 0) {
                    View firstVisibleItemView = mListView.getChildAt(0);
                    //判断第一个条目距离listview是否是0,如果是，则srLayout可用，否则不可用
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        mRefreshLayout.setEnabled(true);
                    } else {
                        mRefreshLayout.setEnabled(false);
                    }
                } else {
                    mRefreshLayout.setEnabled(false);
                }
                //根据当前是否是在刷新数据，来决定是否拦截listview的触摸事件
                return isRefreshing;
            }
        });

    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        if (isButton == true && i == SCROLL_STATE_IDLE) {
            pagerNum++;
            if (pagerNum <= 4) {
                mService = new Retrofit.Builder()
                        .baseUrl("http://live.ximalaya.com")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                        .create(guojiaService.class);
                mService.getList(pagerNum, 20, 3).enqueue(this);
            }
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {
        if (i + i1 == i2) {
            isButton = true;
        } else {
            isButton = false;
        }
    }

    @Override
    public void onResponse(Call<bendiEntity> call, Response<bendiEntity> response) {
        List<bendiEntity.ResultEntity> result = response.body().getResult();
        Log.d("logd", "onResponse: " + result);
        data.addAll(result);
        mAdapter.notifyDataSetChanged();
        mRefreshLayout.setRefreshing(false);
        isRefreshing = false;
    }

    @Override
    public void onFailure(Call<bendiEntity> call, Throwable t) {

    }

    @Override
    public void onClick(View view) {
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Helper helper = new Helper(this);
        SQLiteDatabase db = helper.getReadableDatabase();
        ContentValues values = new ContentValues();
        String title = data.get(position).getRname();
        String name = data.get(position).getProgramName();
        SimpleDateFormat format = new SimpleDateFormat("yyyy"+"年"+"MM" +"月"+"dd"+"日" +"hh:mm:ss");
        String time = format.format(new Date());

        values.put("title", title);
        values.put("name", "上次收听的节目："+name);
        values.put("number", "上次收听的时间："+time);
        db.insert(Helper.TABLE_NAME, null, values);
//        Toast.makeText(this, title +" "+ name +" "+number, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "添加数据库成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRefresh() {
        data.clear();
        mService = new Retrofit.Builder()
                .baseUrl("http://live.ximalaya.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(guojiaService.class);
        pagerNum =1;
        mService.getList(pagerNum, 20, 3).enqueue(this);
        isRefreshing = true;
    }
}
